package com.situ.blog.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.situ.blog.listener.BlogExcelListener;
import com.situ.blog.mapper.BlogMapper;
import com.situ.blog.pojo.entity.Blog;
import com.situ.blog.pojo.vo.BlogExcelVO;
import com.situ.blog.service.IBlogService;
import com.situ.blog.util.ExcelUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Gao
 * @since 2024-09-24
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Autowired
    private BlogMapper blogMapper;

    @Override
    public void exportExcel(HttpServletResponse response) {
        List<Blog> list = blogMapper.selectList(null);
        List<BlogExcelVO> blogExcelVOList = new ArrayList<>();
        for (Blog blog : list) {
            BlogExcelVO blogExcelVO = new BlogExcelVO();
            BeanUtils.copyProperties(blog, blogExcelVO);
            blogExcelVOList.add(blogExcelVO);
        }
        ExcelUtil.exportExcel(response, blogExcelVOList, BlogExcelVO.class, "blog");
    }

    @Override
    public void importExcel(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), BlogExcelVO.class, new BlogExcelListener(blogMapper)).sheet().doRead();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
